package service

import (
	"dynamic-private/pkg/base"
	"dynamic-private/pkg/conf"
	"dynamic-private/pkg/dto"
	"dynamic-private/pkg/po"
	"dynamic-private/pkg/vo"
	"encoding/json"
	"errors"
	"github.com/tristin2024/cl"
	"github.com/tristin2024/logs"
	"time"
	"xorm.io/builder"
)

type dynamicAdminService struct{}

var DynamicAdminService = new(dynamicAdminService)

// GetUserInfoByUserId 通过用户Id获取用户信息
func (da *dynamicAdminService) GetUserInfoByUserId(userId []string) ([]vo.GetUserInfoByDisplayId, error) {
	var resp cl.ClRespModel
	var req dto.GetUserInfoByUserId
	req.UserId = userId
	err := cl.PostJsonStruct(conf.UrlName[conf.UserPrivateApi]+"/api/v1/user-private/info_list", &req, &resp)
	if err != nil {
		logs.Std.Error(err)
		return nil, err
	}
	if resp.Code != 1 {
		return nil, errors.New(resp.Msg)
	}
	var data []vo.GetUserInfoByDisplayId
	a, _ := json.Marshal(&resp.Data)
	err = json.Unmarshal(a, &data)
	if err != nil {
		logs.Std.Error(err)
		return nil, err
	}

	return data, err

}

// GetUserInfoByDisplayID 通过外显Id获取用户信息
func (da *dynamicAdminService) GetUserInfoByDisplayID(displayId []int64) ([]vo.GetUserInfoByDisplayId, error) {
	var resp cl.ClRespModel
	var req dto.GetUserInfoByDisplayId
	for i := range displayId {
		req.DisplayId = append(req.DisplayId, displayId[i])
	}

	err := cl.PostJsonStruct(conf.UrlName[conf.UserPrivateApi]+"/api/v1/user-private/info_list", &req, &resp)
	if err != nil {
		logs.Std.Error(err)
		return nil, err
	}
	if resp.Code != 1 {
		return nil, errors.New(resp.Msg)
	}
	var data []vo.GetUserInfoByDisplayId
	a, _ := json.Marshal(&resp.Data)
	err = json.Unmarshal(a, &data)
	if err != nil {
		logs.Std.Error(err)
		return nil, err
	}

	return data, err
}

// QueryDynamicAdminList 查询动态管理列表
func (da *dynamicAdminService) QueryDynamicAdminList(req *dto.QueryDynamicAdminList) (vo.QueryDynamicAdminListTotal, error) {
	var resp []vo.QueryDynamicAdminList
	var ListTotal vo.QueryDynamicAdminListTotal
	cond := builder.NewCond()
	if req.DisplayId != 0 {
		var displayIds []int64
		displayIds = append(displayIds, req.DisplayId)
		disPlayIdList, err := DynamicAdminService.GetUserInfoByDisplayID(displayIds)
		if err != nil {
			return vo.QueryDynamicAdminListTotal{}, errors.New("获取用户信息失败")
		}
		if len(disPlayIdList) == 0 {
			return vo.QueryDynamicAdminListTotal{}, nil
		}
		cond = cond.And(builder.Eq{"user_id": disPlayIdList[0].UserId})
	}
	if req.StartTime != 0 {
		cond = cond.And(builder.Gte{"created_at": req.StartTime})
	}
	if req.EndTime != 0 {
		cond = cond.And(builder.Lte{"created_at": req.EndTime})
	}
	if req.State != 0 {
		cond = cond.And(builder.Eq{"state": req.State})
	}
	total, err := base.XormEngine.Table(po.PostTable).
		Select("id,user_id,content_text,forward_count,like_count,comment_count,view_count,state,created_at,audited_at,audit_reason,resource_url").
		Where(cond).
		Desc("created_at").
		Limit(req.PageSize, (req.Page-1)*req.PageSize).FindAndCount(&resp)
	if err != nil {
		logs.Std.Error(err)
		return vo.QueryDynamicAdminListTotal{}, errors.New("获取动态信息失败")
	}
	var userIds []string
	for _, v := range resp {
		userIds = append(userIds, v.UserId)
	}
	userInfo, err := DynamicAdminService.GetUserInfoByUserId(userIds)
	if err != nil {
		logs.Std.Error(err)
		return vo.QueryDynamicAdminListTotal{}, errors.New("获取用户信息失败")
	}
	for _, v := range resp {
		tempData := vo.QueryDynamicAdminList{
			Id:           v.Id,
			UserId:       v.UserId,
			ContentText:  v.ContentText,
			State:        v.State,
			CreatedAt:    v.CreatedAt,
			AuditedAt:    v.AuditedAt,
			ForwardCount: v.ForwardCount,
			CommentCount: v.CommentCount,
			LikeCount:    v.LikeCount,
			ViewCount:    v.ViewCount,
			AuditReason:  v.AuditReason,
			ResourceUrl:  v.ResourceUrl,
		}
		for _, v1 := range userInfo {
			if v.UserId == v1.UserId {
				tempData.DisplayId = v1.DisplayId
				tempData.Name = v1.Name
			}
		}
		ListTotal.DynamicList = append(ListTotal.DynamicList, tempData)

	}
	ListTotal.TotalCount = total
	return ListTotal, nil
}

// AuditDynamicAdmin 审核动态
func (da *dynamicAdminService) AuditDynamicAdmin(req *dto.AuditDynamicAdmin) error {
	var ids []int64
	for i := range req.Id {
		ids = append(ids, req.Id[i])
	}
	if req.AuditType == 1 {
		newData := po.Post{
			State:       1,
			AuditedAt:   time.Now().UnixMilli(),
			AuditReason: req.AuditReason,
		}
		_, err := base.XormEngine.Table(po.PostTable).In("id", ids).Update(&newData)
		if err != nil {
			logs.Std.Error(err)
			return errors.New("审核失败")
		}
	} else if req.AuditType == 2 {
		newData := po.Post{
			State:       3,
			AuditedAt:   time.Now().UnixMilli(),
			AuditReason: req.AuditReason,
		}
		_, err := base.XormEngine.Table(po.PostTable).In("id", ids).Update(&newData)
		if err != nil {
			logs.Std.Error(err)
			return errors.New("审核失败")
		}
	}

	return nil
}

// HideDynamicAdmin 隐藏动态
func (da *dynamicAdminService) HideDynamicAdmin(req *dto.HideDynamicAdmin) error {
	var ids []int64
	for i := range req.Id {
		ids = append(ids, req.Id[i])
	}
	if req.HideType == 1 {
		newData := po.Post{
			State:       1,
			AuditedAt:   time.Now().UnixMilli(),
			AuditReason: req.AuditReason,
		}
		_, err := base.XormEngine.Table(po.PostTable).In("id", ids).Update(&newData)
		if err != nil {
			logs.Std.Error(err)
			return errors.New("显示失败")
		}
	} else if req.HideType == 2 {
		newData := po.Post{
			State:       3,
			AuditedAt:   time.Now().UnixMilli(),
			AuditReason: req.AuditReason,
		}
		_, err := base.XormEngine.Table(po.PostTable).In("id", ids).Update(&newData)
		if err != nil {
			logs.Std.Error(err)
			return errors.New("隐藏失败")
		}
	}
	return nil
}

// QueryDynamicCommentAdminList 查询动态评论管理列表
func (da *dynamicAdminService) QueryDynamicCommentAdminList(req *dto.QueryDynamicCommentAdminList) (vo.QueryDynamicCommentAdminListTotal, error) {
	var resp []vo.QueryDynamicCommentAdminList
	var ListTotal vo.QueryDynamicCommentAdminListTotal
	count, err := base.XormEngine.Table(po.CommentTable).Select("id,post_id,user_id,content,created_at,parent_id,parent_user_id,audit_reason,state").
		Limit(req.PageSize, (req.Page-1)*req.PageSize).
		Where("post_id = ?", req.PostId).FindAndCount(&resp)
	if err != nil {
		return vo.QueryDynamicCommentAdminListTotal{}, errors.New("获取动态评论列表失败")
	}
	ListTotal.TotalCount = count
	var userIds []string
	for _, v := range resp {
		userIds = append(userIds, v.UserId)
	}
	userInfo, err := DynamicAdminService.GetUserInfoByUserId(userIds)
	if err != nil {
		logs.Std.Error(err)
		return vo.QueryDynamicCommentAdminListTotal{}, errors.New("获取用户信息失败")
	}
	for i, v := range resp {
		for _, vv := range userInfo {
			if v.UserId == vv.UserId {
				resp[i].CommentUserName = vv.Name
			}
		}
	}
	var parentUserIds []string
	for _, v := range resp {
		parentUserIds = append(parentUserIds, v.ParentUserId)
	}
	parentUserInfo, err := DynamicAdminService.GetUserInfoByUserId(parentUserIds)
	if err != nil {
		logs.Std.Error(err)
		return vo.QueryDynamicCommentAdminListTotal{}, errors.New("获取用户信息失败")
	}
	for i, v := range resp {
		for _, vv := range parentUserInfo {
			if v.ParentUserId == vv.UserId {
				resp[i].ParentUserName = vv.Name
			}
		}
	}
	ListTotal.CommentList = resp
	return ListTotal, nil
}

// AuditDynamicComment 审核动态评论
func (da *dynamicAdminService) AuditDynamicComment(req *dto.AuditDynamicComment) error {
	var ids []int64
	for i := range req.Id {
		ids = append(ids, req.Id[i])
	}
	if req.AuditType == 1 {
		newData := po.Comment{
			State:       1,
			UpdatedAt:   time.Now().UnixMilli(),
			AuditReason: req.AuditReason,
		}
		_, err := base.XormEngine.Table(po.CommentTable).In("id", ids).Update(&newData)
		if err != nil {
			logs.Std.Error(err)
			return errors.New("审核失败")
		}
	} else if req.AuditType == 2 {
		newData := po.Comment{
			State:       3,
			UpdatedAt:   time.Now().UnixMilli(),
			AuditReason: req.AuditReason,
		}
		_, err := base.XormEngine.Table(po.CommentTable).In("id", ids).Update(&newData)
		if err != nil {
			logs.Std.Error(err)
			return errors.New("审核失败")
		}
	}

	return nil
}

// HideDynamicComment 隐藏动态评论
func (da *dynamicAdminService) HideDynamicComment(req *dto.HideDynamicComment) error {
	var ids []int64
	for i := range req.Id {
		ids = append(ids, req.Id[i])
	}
	if req.HideType == 1 {
		newData := po.Comment{
			State:       1,
			UpdatedAt:   time.Now().UnixMilli(),
			AuditReason: req.AuditReason,
		}
		_, err := base.XormEngine.Table(po.CommentTable).In("id", ids).Update(&newData)
		if err != nil {
			logs.Std.Error(err)
			return errors.New("显示失败")
		}
	} else if req.HideType == 2 {
		newData := po.Comment{
			State:       3,
			UpdatedAt:   time.Now().UnixMilli(),
			AuditReason: req.AuditReason,
		}
		_, err := base.XormEngine.Table(po.CommentTable).In("id", ids).Update(&newData)
		if err != nil {
			logs.Std.Error(err)
			return errors.New("隐藏失败")
		}
	}
	return nil
}
